<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\model\dealer;

use app\api\service\User as UserService;
use app\common\model\Order as OrderModel;
use app\common\model\dealer\Order as DealerOrderModel;

/**
 * 分销商订单模型
 * Class Order
 * @package app\api\model\dealer
 */
class Order extends DealerOrderModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'store_id',
        'update_time',
    ];

    /**
     * 获取分销商订单列表
     * @param array $param
     * @return \think\Paginator
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = []): \think\Paginator
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 获取分销商订单列表
        $list = $this->getNewQuery()
            ->with(['user.avatar', 'order'])
            ->where($filter)
            ->where('first_user_id|second_user_id|third_user_id', '=', $userId)
            ->where('is_invalid', '=', 0)
            ->order(['create_time' => 'desc'])
            ->paginate(15);
        // 数据整理
        foreach ($list as &$item) {
            // 我的佣金
            $money = [
                $item['first_user_id'] => $item['first_money'],
                $item['second_user_id'] => $item['second_money'],
                $item['third_user_id'] => $item['third_money'],
            ];
            $item['my_money'] = $money[$userId];
        }
        return $list;
    }

    /**
     * 设置检索查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = []): array
    {
        // 默认参数
        $params = $this->setQueryDefaultValue($param, [
            'settled' => -1, // 是否已结算佣金
        ]);
        // 检索查询条件
        $filter = [];
        // 是否结算佣金
        $params['settled'] > -1 && $filter[] = ['is_settled', '=', (bool)$params['settled']];
        return $filter;
    }

    /**
     * 创建分销商订单记录
     * @param OrderModel $order 订单记录
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createOrder(OrderModel $order): bool
    {
        // 分销订单模型
        $model = new static;
        // 分销商基本设置
        $setting = Setting::getItem('basic');
        // 是否开启分销功能
        if (!$setting['is_open']) {
            return false;
        }
        // 获取当前买家的所有上级分销商用户id
        $dealerUser = $model->getDealerUserId((int)$order['user_id'], (int)$setting['level'], (bool)$setting['self_buy']);
        // 非分销订单
        if (!$dealerUser['first_user_id']) {
            return false;
        }
        // 计算订单分销佣金
        $capital = static::getCapitalByOrder($order);
        // 保存分销订单记录
        return $model->save([
            'user_id' => $order['user_id'],
            'order_id' => $order['order_id'],
            'order_price' => $capital['orderPrice'],
            'first_money' => max($capital['first_money'], 0),
            'second_money' => max($capital['second_money'], 0),
            'third_money' => max($capital['third_money'], 0),
            'first_user_id' => $dealerUser['first_user_id'],
            'second_user_id' => $dealerUser['second_user_id'],
            'third_user_id' => $dealerUser['third_user_id'],
            'is_settled' => 0,
            'store_id' => $model::$storeId
        ]);
    }

    /**
     * 获取当前买家的所有上级分销商用户ID
     * @param int $userId 用户ID
     * @param int $level 推荐等级
     * @param bool $selfBuy 分销商自购
     * @return array
     */
    private function getDealerUserId(int $userId, int $level, bool $selfBuy): array
    {
        $dealerUser = [
            'first_user_id' => $level >= 1 ? Referee::getRefereeUserId($userId, 1, true) : 0,
            'second_user_id' => $level >= 2 ? Referee::getRefereeUserId($userId, 2, true) : 0,
            'third_user_id' => $level == 3 ? Referee::getRefereeUserId($userId, 3, true) : 0
        ];
        // 分销商自购
        if ($selfBuy && User::isDealerUser($userId)) {
            return [
                'first_user_id' => $userId,
                'second_user_id' => $dealerUser['first_user_id'],
                'third_user_id' => $dealerUser['second_user_id'],
            ];
        }
        return $dealerUser;
    }
}
